﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.IO;
using System.Linq;
using System.Net;
using System.Windows;
using Microsoft.Win32;
using VkClientIM.Properties;
using Vkontakte.Api;

namespace VkClientIM
{
	/// <summary>
	/// Interaction logic for App.xaml
	/// </summary>
	public partial class App : Application
	{
		internal VkClientIM.Logic.ApiLogic ApiLogic = null;
		internal Vkontakte.Api.ApiClient ApiClient = null;
		internal IWebProxy Proxy = null;
		internal bool NeedToRoolbackIESettings = false;
		internal Database.ClientDatabase ClientDatabase;
		internal Database.ImageCache ImageCache;
		internal int SavedProxyEnable = -1;
		internal string SavedProxyServer = null;

		protected override void OnStartup(StartupEventArgs e)
		{
			#region Настройка прокси
			switch ( Settings.Default.ProxySettings )
			{
				case 0:
					// Прокси отключен
					SaveIEProxySettings();
					DisableIEProxy();
					HttpWebRequest.DefaultWebProxy = null;
					break;
				case 1:
					// Системные настройки
					HttpWebRequest.DefaultWebProxy = HttpWebRequest.GetSystemWebProxy();
					break;
				case 2:
					// Вручную
					SaveIEProxySettings();
					HttpWebRequest.DefaultWebProxy = new WebProxy( Settings.Default.ProxyAddress, Settings.Default.ProxyPort );
					SetIEProxy( Settings.Default.ProxyAddress, Settings.Default.ProxyPort );
					break;
			}

			if (Settings.Default.ProxySettings != 0)
			{
				switch ( Settings.Default.ProxyAuthSettings )
				{
					case 1:
						HttpWebRequest.DefaultWebProxy.Credentials=CredentialCache.DefaultNetworkCredentials;
						break;
					case 2:
						///
						break;
				}
			}
			#endregion

			string locAppData= Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);

			string appDir = Path.Combine( locAppData, "vkclientIM" );
			if (!Directory.Exists( appDir ))
			{
				Directory.CreateDirectory( appDir );
			}
			try
			{
				ImageCache = Database.ImageCache.OpenOrCreate(Path.Combine(locAppData, "vkclientIM", "image.cache"));
				ImageDownloader.AttachImageCache(ImageCache);
				ClientDatabase = Database.ClientDatabase.OpenOrCreate(Path.Combine(locAppData, "vkclientIM", "client.db"));
			}
			catch ( Exception ex)
			{
				MessageBox.Show( ex.Message );
				App.Current.Shutdown(-1);
			}


			var clientDesktop = new ClientDesktop();

			clientDesktop.Show();
			base.OnStartup( e );
		}

		protected override void OnExit(ExitEventArgs e)
		{
			if (ApiLogic!=null)
			{
				ApiLogic.Close();
				ApiLogic = null;
			}
			base.OnExit(e);
		}

		internal void SaveIEProxySettings()
		{
			RegistryKey registry = Registry.CurrentUser.OpenSubKey("Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings", false);
			SavedProxyEnable = (int)registry.GetValue("ProxyEnable");
			SavedProxyServer = (string)registry.GetValue("ProxyServer");
		}

		internal void RestoreIEProxySettings()
		{
			if (SavedProxyEnable != -1)
			{
				RegistryKey registry =
					Registry.CurrentUser.OpenSubKey( "Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings", true );
				registry.SetValue( "ProxyEnable", SavedProxyEnable, RegistryValueKind.DWord );
				registry.SetValue( "ProxyServer", SavedProxyServer, RegistryValueKind.String );
			}
		}

		internal void DisableIEProxy()
		{
			RegistryKey registry =
				Registry.CurrentUser.OpenSubKey( "Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings", true );
			registry.SetValue( "ProxyEnable", 0, RegistryValueKind.DWord );
		}

		internal void SetIEProxy(string address,int port)
		{
			RegistryKey registry =
				Registry.CurrentUser.OpenSubKey("Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings", true);
			registry.SetValue("ProxyEnable", 1, RegistryValueKind.DWord);
			registry.SetValue("ProxyServer", address+":"+port, RegistryValueKind.String);
		}

		public new static App Current
		{
			get { return (App)Application.Current; }
		}
	}
}
